
package org.scalabletype.ws;

import java.util.ArrayList;
import java.util.Enumeration;

import javax.mail.NoSuchProviderException;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.jets3t.service.S3ServiceException;

import org.scalabletype.data.DataHelper;
import org.scalabletype.data.Blog;
import org.scalabletype.data.User;
import org.scalabletype.util.AuthServer;
import org.scalabletype.util.MailListener;

public class ScalableTypeStarter implements ServletContextListener {
	private AuthServer auth;
	private MailListener mail;

	public void contextInitialized(ServletContextEvent evt) {
		// init data persistence layer
		DataHelper.initDataHelper(evt.getServletContext());

		// now, if we don't have any users installed, create the admin account
		EntityManager em = DataHelper.getEntityManager();
		Query query = em.createQuery("select object(o) from User o limit 1");
		User usr = null;
		if (query.getResultList().size() == 0) {
			// add user
			usr = new User();
			usr.setUsername("admin");
			usr.setPassword("scalable");
			usr.setFirstName("");
			usr.setLastName("");
//			ArrayList<String> groups = new ArrayList<String>();
//			groups.add("admin");
//			groups.add("author");
//			usr.setAuthGroups(groups);
			usr.setAuthGroups("admin");
			em.persist(usr);

			usr = new User();
			usr.setUsername("dkavanagh@gmail.com");
			usr.setPassword("dak");
			usr.setFirstName("David");
			usr.setLastName("Kavanagh");
			usr.setAuthGroups("author");
			em.persist(usr);
		}
		query = em.createQuery("select object(o) from Blog o limit 1");
		if (query.getResultList().size() == 0) {
			Blog blog = new Blog();
			blog.setName("blahblog");
			blog.setTitle("Blah Blog");
			blog.setSlogan("About as much blah as you can take.");
			blog.setAuthors(usr.getId());
//			ArrayList<String> cnames = new ArrayList<String>();
//			cnames.add("blahblog");
//			blog.setCnames(cnames);
			em.persist(blog);
		}
		em.close();

		// start authorization socket listener
		auth = new AuthServer();
		auth.start();

		// start listening for e-mail submissions
		try {
			mail = new MailListener("pop.gmail.com", "scalabletype@gmail.com", "typeisscalable",
							DataHelper.getGlobalStringResource("aws.accessId"),
							DataHelper.getGlobalStringResource("aws.secretKey"),
							DataHelper.getGlobalStringResource("aws.bucket"));
			mail.startListening();
		} catch (NoSuchProviderException ex) {
			ex.printStackTrace();
		} catch (S3ServiceException ex) {
			ex.printStackTrace();
		}
	}

	public void contextDestroyed(ServletContextEvent evt) {
		if (auth != null) {
			auth.interrupt();
			auth = null;
		}
		if (mail != null) {
			mail.stopListening();
			mail = null;
		}
	}
}
